package cn.labelnet.android.roomdb.user

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Toast
import cn.labelnet.android.roomdb.R
import cn.labelnet.android.roomdb.base.data.DbHelper
import cn.labelnet.android.roomdb.base.data.tables.UserTable
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_user_add_page.*

/**
 * Created by yuan on 03/08/2017.
 * 添加用户
 */
class UserAddPageActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_add_page)
        btnInput.setOnClickListener({ view ->
            run {
                // click事件
                val name = etName.text.toString()
                val phone = etPhone.text.toString()
                saveUserInfo(n = name, p = phone)
            }
        })
    }

    /**
     * 保存数据
     */
    private fun saveUserInfo(n: String, p: String) {

        val observable = Observable.create(ObservableOnSubscribe<Boolean> {
            e ->
            run {
                try {
                    DbHelper.INSTANCE!!.getUserDao().insertUser(UserTable(name = n, phone = p))
                    e.onNext(true)
                } catch (ex: Exception) {
                    e.onNext(false)
                    e.onError(ex)
                }
            }
        })

        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    isSuccess ->
                    showMsg(if (isSuccess) "录入成功" else "录入失败")
                }, {
                    e ->
                    Log.e("User", e.message)
                })

    }

    /**
     * 提醒
     */
    private fun showMsg(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }


}